package com.xyz.test

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.DocumentsContract
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.documentfile.provider.DocumentFile
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {

    private val TAG = "xyzTest"
    private val REQUEST_CODE_DIR = 100
    private var currentDirectory: DocumentFile? = null
    private lateinit var statusTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(TAG, "enter MainActivity.onCreate")
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        statusTextView = findViewById(R.id.statusTextView)
        val pickDirButton: Button = findViewById(R.id.pickDirButton)
        val createFileButton: Button = findViewById(R.id.createFileButton)
        val createDirButton: Button = findViewById(R.id.createDirButton)

        // 请求存储权限（Android 6.0+）
        if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
                REQUEST_CODE_DIR
            )
        }

        pickDirButton.setOnClickListener {
            openDirectoryPicker()
        }

        createFileButton.setOnClickListener {
            currentDirectory?.createFile("text/plain", "new_file.txt")?.let { file ->
                Snackbar.make(it, "Created: ${file.name}", Snackbar.LENGTH_SHORT).show()
                refreshDirectoryList()
            }
        }

        createDirButton.setOnClickListener {
            currentDirectory?.createDirectory("NewFolder")?.let { dir ->
                Snackbar.make(it, "Created: ${dir.name}", Snackbar.LENGTH_SHORT).show()
                refreshDirectoryList()
            }
        }
    }

    private fun openDirectoryPicker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
        // 可选：设置初始目录提示
        // intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.parse("content://com.android.externalstorage.documents/document/primary:Downloads"))
        startActivityForResult(intent, REQUEST_CODE_DIR)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_DIR && resultCode == RESULT_OK) {
            data?.data?.let { treeUri ->
                // 持久化权限
                contentResolver.takePersistableUriPermission(
                    treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION or
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                )

                currentDirectory = DocumentFile.fromTreeUri(this, treeUri)
                statusTextView.text = "Current Directory: ${currentDirectory?.name ?: "Root"}"
                refreshDirectoryList()
            }
        }
    }

    private fun refreshDirectoryList() {
        currentDirectory?.listFiles()?.let { files ->
            val sb = StringBuilder("Directory Contents:\n")
            files.forEach { file ->
                sb.append("• ${file.name} (${file.type})\n")
            }
            Log.d("SAF_Demo", sb.toString())
            Snackbar.make(statusTextView, "Updated directory list", Snackbar.LENGTH_LONG)
                .setAction("Show Log") {
                    // 可在此添加日志查看功能
                }.show()
        }
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_DIR && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 权限已授予
        } else {
            Snackbar.make(statusTextView, "Storage permission required", Snackbar.LENGTH_SHORT)
                .show()
        }
    }
}